﻿using DocumentFormat.OpenXml.Math;
using ERP.Common.Results;
using ERP.ERPSystem.HumanResources.Dto;
using ERP.Team.ProductionSystem;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.ProductionSystem
{
    public class MaterialproductmanagementServices:ApplicationService, IMaterialproductmanagementServices
    {
        private readonly IRepository<MaterialType, int> _materialTyperepository;
        private readonly IRepository<MaterialproductModel, int> _materialproductrepository;

        public MaterialproductmanagementServices(IRepository<MaterialType, int> materialTyperepository, IRepository<MaterialproductModel, int> materialproductrepository)
        {
            _materialTyperepository = materialTyperepository;
            _materialproductrepository = materialproductrepository;
        }
        /// <summary>
        /// 添加物料产品管理    
        /// </summary>
        /// <param name="materialproductDTO"></param>
        /// <returns></returns>
        public async Task<int> AddMaterialproductmanagement(MaterialproductDTO materialproductDTO)
        {
            var materialproduct = ObjectMapper.Map<MaterialproductDTO, MaterialproductModel>(materialproductDTO);
            var i = await _materialproductrepository.InsertAsync(materialproduct);
            return i == null ? 0 : 1;
        }
        /// <summary>
        /// 物料产品管理列表
        /// </summary>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<APIPaging<MaterialproductModel>> GetMaterialproductModel(string? code, string? name, int page = 1, int limit = 3)
        {
            try
            {
                APIPaging<MaterialproductModel> pageList = new APIPaging<MaterialproductModel>();
                var MaterialproductModel2 = await _materialproductrepository.GetQueryableAsync();// ((page - 1) * limit, limit, "CreatedAt DESC");
                MaterialproductModel2 = MaterialproductModel2.WhereIf(!string.IsNullOrEmpty(code), m => m.MaterielCode.Contains(code));
                MaterialproductModel2 = MaterialproductModel2.WhereIf(!string.IsNullOrEmpty(name), m => m.MaterielName.Contains(name));
                var MaterialproductModel = MaterialproductModel2.ToList();
                pageList.PageCount = MaterialproductModel2.Count();
                pageList.ListDate = MaterialproductModel2.OrderByDescending(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                pageList.PageIndex = Convert.ToInt32(Math.Ceiling(pageList.PageCount * 1.0 / limit));
                return pageList;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据ID获取物料产品详情
        /// </summary>
        /// <param name="id">物料产品ID</param>
        /// <returns></returns>
        public async Task<MaterialproductModel> GetMaterialproductById(int id)
        {
            try
            {
                var materialproduct = await _materialproductrepository.GetAsync(id);
                return materialproduct;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 更新物料产品管理
        /// </summary>
        /// <param name="materialproductDTO">物料产品DTO</param>
        /// <returns></returns>
        public async Task<int> UpdateMaterialproductmanagement(MaterialproductDTO materialproductDTO)
        {
            try
            {
                if (materialproductDTO == null || materialproductDTO.Id <= 0)
                {
                    Logger.LogWarning("无效的物料产品DTO数据");
                    return 0;
                }

                Logger.LogInformation($"开始更新物料产品，ID: {materialproductDTO.Id}");

                var materialproduct = await _materialproductrepository.FirstOrDefaultAsync(x => x.Id == materialproductDTO.Id);
                if (materialproduct == null)
                {
                    Logger.LogWarning($"未找到ID为 {materialproductDTO.Id} 的物料产品");
                    return 0;
                }

                // 更新字段
                materialproduct.MaterielCode = materialproductDTO.MaterielCode ?? "";
                materialproduct.MaterielName = materialproductDTO.MaterielName ?? "";
                materialproduct.MaterielUrl = materialproductDTO.MaterielUrl ?? "";
                materialproduct.Specifications = materialproductDTO.Specifications ?? "";
                materialproduct.UnitsId = materialproductDTO.UnitsId ?? "";
                materialproduct.MaterielTypePid = materialproductDTO.MaterielTypePid;
                materialproduct.MaterielTypeId = materialproductDTO.MaterielTypeId;
                materialproduct.IsNo = materialproductDTO.IsNo;
                materialproduct.IsSecure = materialproductDTO.IsSecure;
                // 不更新创建时间，保持原有的

                await _materialproductrepository.UpdateAsync(materialproduct, autoSave: true);
                Logger.LogInformation($"成功更新物料产品，ID: {materialproductDTO.Id}");
                return 1;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"更新物料产品失败，ID: {materialproductDTO?.Id}, 错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 删除物料产品
        /// </summary>
        /// <param name="id">物料产品ID</param>
        /// <returns></returns>
        public async Task<int> DeleteMaterialproductmanagement(int id)
        {
            try
            {
                if (id <= 0)
                {
                    Logger.LogWarning("无效的物料产品ID");
                    return 0;
                }

                Logger.LogInformation($"开始删除物料产品，ID: {id}");

                var materialproduct = await _materialproductrepository.FirstOrDefaultAsync(x => x.Id == id);
                if (materialproduct == null)
                {
                    Logger.LogWarning($"未找到ID为 {id} 的物料产品");
                    return 0;
                }

                await _materialproductrepository.DeleteAsync(materialproduct, autoSave: true);
                Logger.LogInformation($"成功删除物料产品，ID: {id}");
                return 1;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"删除物料产品失败，ID: {id}, 错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 批量删除物料产品
        /// </summary>
        /// <param name="ids">物料产品ID列表</param>
        /// <returns></returns>
        public async Task<int> BatchDeleteMaterialproductmanagement(List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    Logger.LogWarning("无效的物料产品ID列表");
                    return 0;
                }

                Logger.LogInformation($"开始批量删除物料产品，数量: {ids.Count}");

                var materialproducts = await _materialproductrepository.GetListAsync(x => ids.Contains(x.Id));
                if (!materialproducts.Any())
                {
                    Logger.LogWarning("未找到要删除的物料产品");
                    return 0;
                }

                await _materialproductrepository.DeleteManyAsync(materialproducts, autoSave: true);
                Logger.LogInformation($"成功批量删除物料产品，数量: {materialproducts.Count}");
                return materialproducts.Count;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"批量删除物料产品失败，错误: {ex.Message}");
                throw;
            }
        }
    }
}


